from asyncio import CancelledError
from datetime import datetime
from loguru import logger
import sys
from core.socket import WebSocketClient

class ClientApp:
    def __init__(self, token):
        self.token = token
        self.client = WebSocketClient(token)
        self.running = True
        self.setup_handlers()

    def setup_handlers(self):
        """设置命令和配置处理器"""
        
        @self.client.on_command('stop')
        async def handle_stop():
            logger.info("收到停止命令")
            self.running = False
            await self.client.stop()
            #sys.exit(0)

        @self.client.on_config_update
        async def handle_config(config):
            logger.info(f"应用配置已更新: {config}")
            # 在这里实现配置更新逻辑
            pass

    async def run(self):
        """运行应用"""
        try:
            await self.client.start()
        except Exception as e:
            logger.error(f"应用运行错误: {e}")
        except CancelledError:
            logger.info("应用被用户中断")
        finally:
            self.running = False
            